import React, { memo, createContext, useState, useMemo, useEffect } from 'react';
import { history } from 'umi';
import { Transition } from 'react-transition-group';
import './index.less';

const transferTime = 300;
const { Provider, Consumer } = createContext();
const classNames = {
  entering: 'component-enter component-enter-active',
  entered: 'component-enter-active',
  exiting: 'component-exit component-exit-active',
  exited: 'component-exit-active component-exit-hide',
};

export const PageWrapper = ({ children }) => {
  const activePath = history.location.pathname;
  const { defaultPath, basePath } = useMemo(() => {
    const currentPathnameList = React.Children.map(children, (item) => item?.props?.path) || [];
    const currentDefaultPath = _.includes(currentPathnameList, activePath) ? activePath : null;
    const currentBasePath = activePath.replace(/\/\w+$/, '');

    return { defaultPath: currentDefaultPath, basePath: currentBasePath };
  }, []);
  const [pathList, setPathList] = useState([]);

  useEffect(() => {
    const reg = new RegExp('^' + basePath);
    if (reg.test(activePath)) {
      setPathList((currentPathList) => {
        if (currentPathList.length) {
          const index = _.indexOf(currentPathList, activePath);
          if (index > -1) {
            if (index === currentPathList.length - 1) {
              return currentPathList;
            }
            return currentPathList.slice(0, index + 1);
          }
          return [...currentPathList, activePath];
        }
        return defaultPath ? [defaultPath] : [];
      });
    }
  }, [activePath]);

  return (
    <div className="transfer-component-container">
      <Provider value={{ pathList }}>{children}</Provider>
    </div>
  );
};

const ComponentItem = memo(({ path, children }) => {
  const [renderStatus, setRenderStatus] = useState(false);

  return (
    <Consumer>
      {({ pathList }) => {
        const isRender = _.includes(pathList, path);
        const isActive = isRender && path === _.last(pathList);
        if (isRender) {
          if (!renderStatus) {
            setRenderStatus(true);
          }
        } else {
          setTimeout(() => {
            if (renderStatus) {
              setRenderStatus(false);
            }
          }, transferTime);
        }
        return (
          <Transition in={isActive} timeout={transferTime}>
            {(state) => (
              <div
                className={`
                  component-${isActive ? 'active' : 'inactive'}-begin
                  ${classNames[state]}
                `}
              >
                {renderStatus && children}
              </div>
            )}
          </Transition>
        );
      }}
    </Consumer>
  );
});

export default ComponentItem;
